package middlewares

import (
	"source-admin-go/pkg/e"
	"source-admin-go/pkg/httptool"
	"source-admin-go/src/models"

	"github.com/gin-gonic/gin"
)

// Auth中间件
func Auth() gin.HandlerFunc {
	return func(context *gin.Context) {
		RegisterRules(context)
	}
}

// 注册相关规则
func RegisterRules(context *gin.Context) {
	TokenValidation(context)
}

// token验证规则
func TokenValidation(context *gin.Context) {
	appG := httptool.Gin{Context: context}
	var token string
	// 获取header参数
	token = context.Request.Header.Get("Authorization")
	if token == "" {
		// 获取get参数
		token = context.DefaultQuery("token", "")
	}

	checkedToken, err := models.TokenModel{}.TokenValidation(token)

	if checkedToken != nil && checkedToken.ID == 0 || err != nil {
		appG.Response(e.AUTH_FAILED, []interface{}{})
		context.Abort()
		return
	}
	context.Set("user", checkedToken)
	context.Next()
}
